package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.common.CustomException;
import com.project.entity.Category;
import com.project.entity.Dish;
import com.project.entity.Setmeal;
import com.project.mapper.CategoryMapper;
import com.project.service.CategoryService;
import com.project.service.DishService;
import com.project.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类，删除之前需要进行判断
     * @param id
     */
    @Override
    public void remove(Long id) {
        // 创建条件对象
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        // 查询
        int count1 = dishService.count(dishLambdaQueryWrapper);
        // 判断是否关联了菜品
        if(count1 > 0) {
            // 抛出异常
            throw new CustomException("当前分类关联了菜品，无法删除");
        }

        // 创建条件对象
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        // 查询
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        // 判断是否关联了套餐
        if(count2 > 0) {
            // 抛出异常
            throw new CustomException("当前分类关联了套餐，无法删除");
        }

        // 删除
        super.removeById(id);
    }
}
